﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Data.Xml.Dom;
using Windows.Foundation;
using Windows.UI.Notifications;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Media;

namespace Timer
{
    partial class MainPage
    {
        public MainPage()
        {
            timer.Interval = new TimeSpan(0, 0, 0, 0, 100);
            timer.Tick += TimerTick;

            InitializeComponent();
            for (int i = 0; i < 9; i++)
            {
                Hours.Items.Add(i.ToString());
            }
            Hours.SelectedIndex = 0;
            for (int i = 0; i <= 60; i++)
            {
                Minutes.Items.Add(i.ToString());
            }
            Minutes.SelectedIndex = 5;
            for (int i = 0; i <= 60; i++)
            {
                Seconds.Items.Add(i.ToString());
            }
            Seconds.SelectedIndex = 0;
        }

        private void TimerTick(object sender, object e)
        {
            var duration = DateTime.Now - startDate;
            var d = (timeSpan - duration);
            string s = d.ToString("h\\:mm\\:ss");
            if (s != DurationText.Text) DurationText.Text = s;
            // fire this once and only once if the timer is overtime
            if (d.Ticks <= 0 && !overtime) {
                LayoutRoot.Background = new SolidColorBrush(ColorHelper.FromArgb(255, 255, 0, 0));
                overtime = true;
            }
        }

        DateTime startDate;
        DispatcherTimer timer = new DispatcherTimer();
        TimeSpan timeSpan;
        bool overtime;
        TimerState timerState = TimerState.Stopped;

        private enum TimerState
        {
            Running,
            Stopped
        }
        
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            LayoutRoot.Background = new SolidColorBrush(ColorHelper.FromArgb(255, 12, 12, 12));
            if (timerState == TimerState.Stopped)
            {
                overtime = false;
                int hours = Convert.ToInt32(Hours.SelectedIndex);
                int minutes = Convert.ToInt32(Minutes.SelectedIndex);
                int seconds = Convert.ToInt32(Seconds.SelectedIndex);
                var duration = new TimeSpan(hours, minutes, seconds);
                timeSpan = duration;
                startDate = DateTime.Now;
                timer.Start();
                Button.Content = "Reset";

                SetToast(duration);

                timerState = TimerState.Running;
            } else if (timerState == TimerState.Running)
            {
                timer.Stop();
                RemoveToast();
                Button.Content = "Start";
                DurationText.Text = "0:00:00";
                timerState = TimerState.Stopped;
            }
        }

        private static void RemoveToast()
        {
            ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();
            IReadOnlyList<IScheduledToastNotification> scheduledToasts = notifier.GetScheduledToastNotifications();
            int scheduledCount = scheduledToasts.Count;
            for (int i = 0; i < scheduledCount; i++)
            {
                ScheduledToastNotification scheduledToast = (ScheduledToastNotification)scheduledToasts[i];
                if (scheduledToast.Id == "Timer_1")
                {
                    notifier.RemoveFromSchedule(scheduledToast);
                }
            }
        }

        private static void SetToast(TimeSpan timeSpan)
        {
            try
            {
                XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

                XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
                stringElements.Item(0).AppendChild(toastXml.CreateTextNode("Timer hit zero"));

                var displayTime = DateTimeOffset.UtcNow + timeSpan;

                var scheduledToast = new ScheduledToastNotification(toastXml, displayTime);
                scheduledToast.Id = "Timer_1";

                IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
                XmlElement audioElement = toastXml.CreateElement("audio");

                audioElement.SetAttribute("src", "ms-winsoundevent:Notification.Looping.Alarm");
                audioElement.SetAttribute("loop", "true");
                
                toastNode.AppendChild(audioElement);

                ToastNotifier notifier = ToastNotificationManager.CreateToastNotifier();
                notifier.AddToSchedule(scheduledToast);
            }
            catch (Exception ex)
            {
                ex.ToString();
            }
        }
    }
}
